package jsf;

import java.io.Serializable;
import java.util.ArrayList;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import util.SessionUtil;
import ejb.SubjectsBeanRemote;
import entity.Subjects;

@RequestScoped
@ManagedBean
public class SubjectsController implements Serializable {

	private static final long serialVersionUID = 1L;
	@EJB(lookup="java:global/EnrollmentManagementEAP/EnrollmentManagementEJB/SubjectsBean!ejb.SubjectsBeanRemote")
	SubjectsBeanRemote bean;
	private Long selectedId;
	private ArrayList<Subjects> subjects = new ArrayList<Subjects>();
	private Subjects subject = new Subjects();
	
	public SubjectsController() {
		SessionUtil.authenticate();
	}
	
	public ArrayList<Subjects> getSubjects() {
		ArrayList<Subjects> subjects = new ArrayList<Subjects>();
		subjects.addAll(bean.getAll());
		this.subjects = subjects;
		return this.subjects;
	}
	
	public Subjects getSubject() {
		return this.subject;
	}
	
	private Long getSelectedId() {
        ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
        return Long.parseLong(context.getRequestParameterMap().get("selectedId"));
    }
	
	public String edit() {
        selectedId = this.getSelectedId();
        if(selectedId != null) {
            this.subject = this.bean.get(selectedId);
            return "subject.xhtml";
        }
        return "subjects.xhtml";
    }
	
	// For Index Form
	public String create() {
		this.selectedId = null;
        this.subject = new Subjects();
        return "subject.xhtml";
    }
	
	// For Edit Form
	public String doSubmit() {
        if(selectedId == null) {
            return this.doCreate();
        } else {
            return this.doEdit();
        }
    }
	
	// For Edit Form
	public String doEdit() {
        this.bean.update(this.subject);
        return "subjects.xhtml";
    }
    
	// For Edit Form
    public String doCreate() {
    	this.bean.insert(this.subject);
        return "subjects.xhtml";
    }
	
    // For Index Form
	public void doDelete() {
        Long selectedId = this.getSelectedId();
        Subjects selectedSubject = this.bean.get(selectedId);
        if(selectedSubject != null) {
            this.bean.delete(selectedSubject);
        }
    }
}
